package model

import (
	"context"
	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ SysDictModel = (*customSysDictModel)(nil)

type (
	// SysDictModel is an interface to be customized, add more methods here,
	// and implement the added methods in customSysDictModel.
	SysDictModel interface {
		sysDictModel
		Page(ctx context.Context, page uint64, limit uint64, pageSize uint64) (uint32, []*SysDict, error)
	}

	customSysDictModel struct {
		*defaultSysDictModel
	}
)

// NewSysDictModel returns a model for the database table.
func NewSysDictModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) SysDictModel {
	return &customSysDictModel{
		defaultSysDictModel: newSysDictModel(conn, c, opts...),
	}
}

func (m *customSysDictModel) Page(ctx context.Context, page uint64, limit uint64, pageSize uint64) (uint32, []*SysDict, error) {

	statementBuilder := squirrel.StatementBuilder

	//查询列表
	pageSqlBuilder := statementBuilder.Select(sysUserRows).From(m.table).Limit(limit).Offset((page - 1) * limit).OrderBy("id desc")

	query, args, err := pageSqlBuilder.ToSql()
	if err != nil {
		return 0, nil, err
	}
	var resp []*SysDict
	err = m.CachedConn.QueryRowsNoCacheCtx(ctx, &resp, query, args...)
	if err != nil {
		return 0, nil, err
	}

	//查询总数
	countSqlBuilder := statementBuilder.Select("count(id)").From(m.table)
	if err != nil {
		return 0, nil, err
	}
	queryCount, args, err := countSqlBuilder.ToSql()
	var count uint32

	if err := m.CachedConn.QueryRowNoCacheCtx(ctx, &count, queryCount, args); err != nil {
		return 0, nil, err
	}

	return count, resp, nil

}
